package com.century.sjt.activity.login;

import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.century.sjt.EMChat.widget.EaseSidebar;
import com.century.sjt.R;
import com.century.sjt.activity.BaseActivity;
import com.century.sjt.activity.MainActivity;
import com.century.sjt.adapter.ItemMoreAdapter;
import com.century.sjt.util.Constant;
import com.century.sjt.util.TipUtil;
import com.century.sjt.utils.PreferenceManager;
import com.century.sjt.widget.TitleBar.SjtTitleBar;

import org.json.JSONArray;
import org.json.JSONObject;
import org.json.JSONTokener;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

/**
 * Created by asus on 2016/9/28.
 */

public class ChooseCurrencyActivity extends BaseActivity{

    private SjtTitleBar titleBar;
    private ListView mList;
    private Boolean isDataChangeOk=false;
    private List<Map<String, Object>> dataList;
    private ItemMoreAdapter adapter;
    protected EaseSidebar sidebar;
    SharedPreferences mainSharedPreferences;
    Context mContext;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_choosecountry);
        initView();
        initEvent();
    }
    @Override
    protected void initView() {
        mContext=this;
        titleBar = (SjtTitleBar) findViewById(R.id.title_bar);
        titleBar.setTitle(getResources().getString(R.string.text_set_currency));
        titleBar.setLeftLayoutClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (isDataChangeOk){
                    finish();
                }else {
                    AlertDialog.Builder builder = new AlertDialog.Builder(ChooseCurrencyActivity.this);
                    builder.setMessage(getResources().getString(R.string.text_set_currency_isno));
                    builder.setCancelable(true);
                    builder.setPositiveButton(getResources().getString(R.string.btn_yes), new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    });
                    builder.setCancelable(false);
                    builder.create().show();
                }
            }
        });
//        titleBar.setRightIconResourc(getResources().getString(R.string.btn_yes));
        mList = (ListView) findViewById(R.id.list);
        sidebar = (EaseSidebar) findViewById(R.id.sidebar);
        sidebar.setVisibility(View.GONE);
    }

    @Override
    protected void initEvent() {
        dataList = new ArrayList<Map<String, Object>>();
        adapter = new ItemMoreAdapter(ChooseCurrencyActivity.this,dataList,"currency");
        mList.setAdapter(adapter);
        mList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                Map map = (Map) dataList.get(i);
                String sysId = (String) map.get("sysId");
                String mcode = (String) map.get("code");
                String numberCode = (String) map.get("numberCode");
                String chineseName = (String) map.get("name");
                String systemSupport = (String) map.get("systemSupport");
                setCurrency(numberCode,mcode);

            }
        });
        sidebar.setListView(mList);
//
    }

    @Override
    protected void initData() {
        getCurrency();
    }

    @Override
    protected void onResume() {
        super.onResume();
        initData();
    }

    @Override
    protected void onStart() {
        super.onStart();
    }


    private void getCurrency(){
        Locale locale = getResources().getConfiguration().locale;
        final String language = locale.getLanguage();
//        TipUtil.openProgressDialog(Constant.APPLICATION_NAME, getResources().getString(R.string.please_waitting), AddressManageActivity.this);
        StringRequest stringRequest = new StringRequest(Request.Method.POST, Constant.getCurrency, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {
//                    TipUtil.closeProgressDialog();
                    TipUtil.log("接口成功返回", response.toString(), 1);
                    JSONTokener jsonParser = new JSONTokener(response);
                    JSONObject res = (JSONObject) jsonParser.nextValue();
                    String code = res.getString("code");
                    String message = res.getString("message");
                    if (code.equals("200")) {//成功
                        dataList.clear();
                        JSONObject Data = res.getJSONObject("data");
                        JSONArray currencyList = Data.getJSONArray("currencyList");
                        for (int i = 0; i < currencyList.length(); i++) {
                            JSONObject aData = (JSONObject) currencyList.get(i);
                            String sysId = aData.getString("sysId");
                            String mcode = aData.getString("code");
                            String numberCode = aData.getString("numberCode");
                            String chineseName = aData.getString("chineseName");
                            String systemSupport = aData.getString("systemSupport");
                            Map<String, Object> map = new HashMap<String, Object>();
                            map.put("sysId", sysId);
                            map.put("code", mcode);
                            map.put("numberCode", numberCode);
                            map.put("name", chineseName);
                            map.put("systemSupport", systemSupport);
                            dataList.add(map);
                        }
                    } else {//失败
                        TipUtil.showToast(message, ChooseCurrencyActivity.this, 1);
                    }
//                    getMContactList(mDatalist);
                } catch (Exception ex) {
                    ex.printStackTrace();
                    TipUtil.showToast(getResources().getString(R.string.error_service), ChooseCurrencyActivity.this, 1);
                }
                adapter.notifyDataSetChanged();
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                TipUtil.showToast(getResources().getString(R.string.error_network), ChooseCurrencyActivity.this, 1);
                TipUtil.closeProgressDialog();
                adapter.notifyDataSetChanged();
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> map = new HashMap<String, String>();
//                SharedPreferences mainSharedPreferences = getSharedPreferences(Constant.TAG, Activity.MODE_PRIVATE);
//                String userId = mainSharedPreferences.getString("userId", "");
//                map.put("code", language);

                return map;
            }
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                SharedPreferences mainSharedPreferences = getSharedPreferences(Constant.TAG, Activity.MODE_PRIVATE);
                String cookie = mainSharedPreferences.getString("cookie", "");
                String rememberMeValue = mainSharedPreferences.getString("rememberMe", "");
                HashMap localHashMap = new HashMap();
                String cookieValue = cookie + ";" + rememberMeValue;
                localHashMap.put("Cookie", cookieValue);
                return localHashMap;
            }
        };
        mQueue.add(stringRequest);

    }
    private void setCurrency(final String numberCode,final String mCode){
        Locale locale = getResources().getConfiguration().locale;
        final String language = locale.getLanguage();
//        TipUtil.openProgressDialog(Constant.APPLICATION_NAME, getResources().getString(R.string.please_waitting), AddressManageActivity.this);
        StringRequest stringRequest = new StringRequest(Request.Method.POST, Constant.setCurrency, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                try {
//                    TipUtil.closeProgressDialog();
                    TipUtil.log("接口成功返回", response.toString(), 1);
                    JSONTokener jsonParser = new JSONTokener(response);
                    JSONObject res = (JSONObject) jsonParser.nextValue();
                    String code = res.getString("code");
                    String message = res.getString("message");
                    if (code.equals("200")) {//成功
                        PreferenceManager.getInstance().setCurrency(numberCode);
                        PreferenceManager.getInstance().setCountryCode(mCode);
                        Intent intent = new Intent();
                        Bundle bundle = new Bundle();
                        bundle.putString("currency",numberCode);
                        bundle.putString("currencyCode",mCode);
                        intent.putExtras(bundle);
                        ChooseCurrencyActivity.this.setResult(RESULT_OK, intent);
                        finish();
                    } else {//失败
                        TipUtil.showToast(message, ChooseCurrencyActivity.this, 1);
                    }
//                    getMContactList(mDatalist);
                } catch (Exception ex) {
                    ex.printStackTrace();
                    TipUtil.showToast(getResources().getString(R.string.error_service), ChooseCurrencyActivity.this, 1);
                }
                adapter.notifyDataSetChanged();
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                TipUtil.showToast(getResources().getString(R.string.error_network), ChooseCurrencyActivity.this, 1);
                TipUtil.closeProgressDialog();
                adapter.notifyDataSetChanged();
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> map = new HashMap<String, String>();
                SharedPreferences mainSharedPreferences = getSharedPreferences(Constant.TAG, Activity.MODE_PRIVATE);
                String userId = mainSharedPreferences.getString("userId", "");
                map.put("loginId", userId);
                map.put("numberCode", numberCode);
                return map;
            }
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                SharedPreferences mainSharedPreferences = getSharedPreferences(Constant.TAG, Activity.MODE_PRIVATE);
                String cookie = mainSharedPreferences.getString("cookie", "");
                String rememberMeValue = mainSharedPreferences.getString("rememberMe", "");
                HashMap localHashMap = new HashMap();
                String cookieValue = cookie + ";" + rememberMeValue;
                localHashMap.put("Cookie", cookieValue);
                return localHashMap;
            }
        };
        mQueue.add(stringRequest);

    }
}
